/**
 * Project Name:fastPlat
 * File Name:DictionaryServiceImpl.java
 * Package Name:com.fast.user.service.admin.impl
 * Date:2014年12月17日上午11:08:21
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
*/
/**
 * Project Name:fastPlat
 * File Name:DictionaryServiceImpl.java
 * Package Name:com.fast.user.service.admin.impl
 * Date:2014年12月17日上午11:08:21
 * Copyright (c) 2014, chenzhou1025@126.com All Rights Reserved.
 *
 */

package com.fast.cms.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fast.base.dao.daoSuport.JpaDaoSupport;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.db.sql.impl.SqlGeneratorImpl;
import com.fast.cms.model.system.Dictionary;
import com.fast.cms.service.system.DictionaryService;

/**
 * ClassName: DictionaryServiceImpl <br/>
 * Reason:数据字典<br/>
 * date:2014年12月17日 上午11:08:21 <br/>
 * @author Administrator
 * @version 
 * @since JDK 1.6
 */
@Service("dictionaryService")
public class DictionaryServiceImpl extends JpaDaoSupport implements DictionaryService {
	
	/**
	 * 保存与修改数据
	 * @param dictionary
	 * @return
	 */
	@Override
	@CacheEvict(value="dictionary",allEntries=true)
	public Dictionary saveOrUpdateDictionary(Dictionary dictionary){
		return super.merge(dictionary);
	}
	
	/**
	 * 得到字典数据，主要用于下拉框选择用
	 * 此方法包含子链接数据
	 * @throws Exception
	 */
	public List<Map<String, Object>> getDicListWithChildsForSelecter(String parentUUID){
		List<Dictionary> dicList = getDicListWithAllChilds(parentUUID);
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		Map<String,Object> map = null;
		for (Dictionary dictionary : dicList) {
			map = new HashMap<String,Object>();
			map.put("code", dictionary.getUuid());
			map.put("name", dictionary.getDicname());
			mapList.add(map);
		}
		return mapList;
	}
	
	/**
	 * 获取某个分类下的所有信息包括子类信息
	 * @param parentUUID
	 * @param dicAllList
	 * @return
	 */
	@Override
	@Cacheable(value = "dictionary",key="'getDicListWithAllChilds'+#parentUUID")  
	public List<Dictionary> getDicListWithAllChilds(String parentUUID){
		List<Dictionary> dicList = super.queryForBeanList(Dictionary.class, " where parentUUID='" + parentUUID + "' and locked=1 order by sortid asc");
		List<Dictionary> dataList = new ArrayList<Dictionary>();
		if (dicList.size() > 0) {
			for (Dictionary dic : dicList) {
				dataList.add(dic);
				// 判断是否存在下级
				boolean flag = super.isExist(Dictionary.class,"where parentUUID='" + dic.getUuid() + "'");
				if (flag) {
					//递归回调
					List<Dictionary> childs = getDicListWithAllChilds(dic.getUuid());
					for (Dictionary child : childs) {
						child.setDicname("|-"+child.getDicname());
					}
					dataList.addAll(childs);
				}
			}
		}
		return dataList;
	}
	
	/**
	 * 通过父类UUID来获取子类列表
	 * @param parentUUID
	 * @return
	 */
	@Cacheable(value = "dictionary",key="#parentUUID")  
	public List<Map<String, Object>> getDictionaryListByParentUUID(String parentUUID){
		return this.queryForMapList("uuid as code,dicName as name",SqlGeneratorImpl.getTableName(Dictionary.class), "where parentUUID='"+parentUUID+"'");
	}
	
	/**
	 * 取的某分类下的所有值
	 */
	public List<Map<String, Object>> getDicTreeList(String parentUUID){
		return this.getDicTreeList(parentUUID, "uuid,parentUUID,parentName,dicCode,dicname,aliasName,dicdesc");
	}
	
	public List<Map<String, Object>> getDicTreeList(String parentUUID,String fields){
		//查出当前列表
		String sql = "select "+fields+" from "
				+ AbstractSqlGenerator.getTableName(Dictionary.class)
				+ " where parentUUID='" + parentUUID + "' and locked=1 order by sortid asc";
		List<Map<String, Object>> permissionList = super.queryForMapList(sql);
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		if (permissionList.size() > 0) {
			for (Map<String, Object> map : permissionList) {
				// 判断是否存在下级
				boolean flag = super.isExist(Dictionary.class,"where parentUUID='" + map.get("uuid") + "'");
				if (flag) {
					//递归回调
					map.put("children",getDicTreeList(map.get("uuid").toString(),fields));
				}else{
					map.put("children",null);
				}
				// 新增属性对象
				// 添加其它属性
				dataList.add(map);
			}
		}
		return dataList;
	}

	/**
	 * 得到字典树状结构数据
	 * TODO 简单描述该方法的实现功能（可选）.
	 * @see com.fast.cms.service.system.DictionaryService#getDicTreeData(java.lang.String)
	 */
	@Override
	public JSONArray getDicTreeData(String parentUUID,boolean isRoot) {
		if(parentUUID.equals("0")){
			JSONObject jsonOBject = new JSONObject();
			jsonOBject.put("id", 0);
			jsonOBject.put("text", "字典根目录");
			jsonOBject.put("iconCls", "icon-folderPage");
			jsonOBject.put("children", getDicTreeJsonData("0"));
			//新增属性对象
			JSONObject attributes = new JSONObject();
			attributes.put("parentUUID","0");
			attributes.put("parentTitle","最上层");
			attributes.put("dicCode","DIC");
			//添加其它属性
			jsonOBject.put("attributes", attributes);
			JSONArray jsonArray = new JSONArray();
			jsonArray.add(jsonOBject);
			return jsonArray;
		}else{
			if(isRoot){
				Dictionary dic = super.queryForBeanByUUID(Dictionary.class, parentUUID);
				JSONObject jsonOBject = new JSONObject();
				jsonOBject.put("id", dic.getUuid());
				jsonOBject.put("text", dic.getDicname());
				jsonOBject.put("iconCls", "icon-folderPage");
				jsonOBject.put("children", getDicTreeJsonData(parentUUID));
				//新增属性对象
				JSONObject attributes = new JSONObject();
				attributes.put("parentUUID",dic.getParentUUID());
				attributes.put("parentTitle",dic.getParentName());
				attributes.put("dicCode",dic.getDicCode());
				//添加其它属性
				jsonOBject.put("attributes", attributes);
				JSONArray jsonArray = new JSONArray();
				jsonArray.add(jsonOBject);
				return jsonArray;
			}else{
				return getDicTreeJsonData(parentUUID);
			}
			
		}
	}
	
	
	
	/**
	 * getTreeJson:(得到字典树结构数据). <br/>
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	public JSONArray getDicTreeJsonData(String parentUUID){
		//查出当前列表
		String sql = "select uuid,parentUUID,parentName,dicCode,dicname,aliasName,dicdesc from "+AbstractSqlGenerator.getTableName(Dictionary.class)+" where parentUUID='"+parentUUID+"' order by sortid asc";
		List<Map<String, Object>> permissionList = super.queryForMapList(sql);
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonOBject = null;
		if(permissionList.size()>0){
			for (Map<String, Object> map : permissionList) {
				    jsonOBject = new JSONObject();
				    jsonOBject.put("id", map.get("uuid"));
					jsonOBject.put("text",map.get("dicname"));
					//判断是否存在下级
					boolean flag = super.isExist(Dictionary.class,"where parentUUID='"+map.get("uuid")+"'");
					if(flag){
						jsonOBject.put("state","closed");
						jsonOBject.put("iconCls", "icon-folderPage");
						//递归回调
						//jsonOBject.put("children", getPsmTreeJsonData(map.get("uuid").toString()));
					}else{
						jsonOBject.put("iconCls", "icon-page");
					}
					//新增属性对象
					JSONObject attributes = new JSONObject();
					attributes.put("parentUUID",map.get("parentUUID"));
					attributes.put("parentName",map.get("parentName"));
					attributes.put("dicCode",map.get("dicCode"));
					//添加其它属性
					jsonOBject.put("attributes", attributes);
					jsonArray.add(jsonOBject);
			}
		}
		return jsonArray;
	}
	
	/**
	 * 得到树状表格数据
	 * @param parentUUID
	 * @return
	 */
	public JSONArray getTreeGridData(String parentUUID){
		if(parentUUID.equals("0")){
			Dictionary root = new Dictionary();
			root.setId(0);
			root.setUuid("0");
			root.setParentName("-1");
			root.setParentUUID("-1");
			root.setDicCode("-1");
			root.setDicname("字典根目录");
			root.setDicdesc("#");
			JSONObject rootJo = (JSONObject) JSONObject.toJSON(root);
			rootJo.put("iconCls","icon-folderPage");
			JSONArray jsonArray = new JSONArray();
			rootJo.put("children", getTreeGridList(parentUUID));
			jsonArray.add(rootJo);
			return jsonArray;
		}else{
			return getTreeGridList(parentUUID);
		}
	}
	
	private JSONArray getTreeGridList(String parentUUID) {
		JSONArray jsonArray = new JSONArray();
		List<Dictionary> dicList = this.queryForBeanList(Dictionary.class, " where parentUUID='"+parentUUID+"' and locked=1 order by sortid asc");
		if(null!=dicList&&!dicList.isEmpty()){
			JSONObject jsonObject = null;
			for (Dictionary dic : dicList) {
				jsonObject = (JSONObject) JSONObject.toJSON(dic);
				if(super.isExist(Dictionary.class, " where parentUUID='"+dic.getUuid()+"'")){
					jsonObject.put("state","closed");
					jsonObject.put("iconCls","icon-folderPage");
				}else{
					jsonObject.put("iconCls","icon-page");
				}
				jsonArray.add(jsonObject);
			}
		}
		return jsonArray;
	}

	/**
	 * 标题：getSortId  <br/>
	 * 作用：得到排序ID  <br/>
	 * @author developer-lushuifa
	 * @param parentUUID
	 * @return
	 * @since JDK 1.6
	 */
	public int getSortId(String parentUUID){
		try {
			return this.countBySql("select max(sortid) sortid from "+AbstractSqlGenerator.getTableName(Dictionary.class)+" where parentUUID='"+parentUUID+"'")+1;
		} catch (Exception e) {
			return 0;
		}
	}
	
	/**
	 * 标题：genDicDepth <br/>
	 * 作用：  获取深度   <br/>
	 * @author developer-lushuifa
	 * @param parentUUID
	 * @return
	 * @since JDK 1.6
	 */
	public int genDicDepth(String parentUUID){
		try {
			if(parentUUID.equals("0")){
				return 1;
			}else{
				Dictionary parent = this.queryForBean(Dictionary.class, " where uuid='"+parentUUID+"'");
			    return parent.getDepth()+1;
			}
		} catch (Exception e) {
			return 1;
		}
	}

	/**
	 * 标题：getDicDir <br/>
	 * 作用： 获取字典目录    <br/>
	 * @author developer-lushuifa
	 * @param uuid
	 * @return
	 * @since JDK 1.6
	 */
	@Override
	public String getDicDir(String dir,String parentUUID) {
		Dictionary dic = this.queryForBeanByUUID(Dictionary.class,parentUUID);
		dir=dic.getDicname()+"<<"+dir;
		System.out.println(dir);
		if(this.isExist(Dictionary.class, " where uuid='"+dic.getParentUUID()+"'")){
			dir=getDicDir(dir,dic.getParentUUID());
		}
		String rebackStr = dir;
		return rebackStr;
	}
}

